package com.wfh.mianshiji.ai.advisor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import reactor.core.publisher.Flux;

/**
 * @Title: MyLoggerAdvisor
 * @Author wangfenghuan
 * @Package com.wfh.mianshiji.ai.advisor
 * @Date 2025/10/31 18:54
 * @description:
 */
@Slf4j
public class MyLoggerAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

    private AdvisedRequest before(AdvisedRequest advisedRequest) {
        log.info("AI Request: {}", advisedRequest.userText());
        return advisedRequest;
    }

    private void observeAfter(AdvisedResponse advisedResponse) {
        log.info("AI Response: {}", advisedResponse.response().getResult().getOutput().getText());
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        advisedRequest = this.before(advisedRequest);
        try {
            AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);
            this.observeAfter(advisedResponse);
            return advisedResponse;
        } catch (Exception e) {
            log.error("AI Call Failed! Request: {}, Error: {}", advisedRequest.userText(), e.getMessage(), e);
            throw e; // rethrow
        }
    }


    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        advisedRequest = this.before(advisedRequest);
        Flux<AdvisedResponse> advisedResponses = chain.nextAroundStream(advisedRequest);

        // 用于聚合完整响应内容
        StringBuilder fullResponse = new StringBuilder();

        return advisedResponses
                .doOnNext(advisedResponse -> {
                    String content = advisedResponse.response().getResult().getOutput().getText();
                    if (content != null) {
                        fullResponse.append(content);
                    }
                })
                .doOnComplete(() -> {
                    log.info("AI Stream Full Response: {}", fullResponse.toString());
                });
    }
}
